package com.hmyd.hmyd_android.ui;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.adapter.BillRedeemListAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dialog.NormalDialog;
import com.hmyd.hmyd_android.dialog.NormalDialogListener;
import com.hmyd.hmyd_android.dto.BillRedeemData;
import com.hmyd.hmyd_android.dto.Error;
import com.hmyd.hmyd_android.dto.InfoWithError;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * 票据赎回
 * @author wangk
 */

@ContentView(R.layout.activity_bill_redeem)
public class BillRedeemActivity extends BasicActivity implements NormalDialogListener {

	private final int POST_BILL_REDEEM = 2; // 请求赎回
	private final int GET_BILL_LIST = 3;

	@ViewInject(R.id.layout_home_title)
	private RelativeLayout layout_home_title;
	@ViewInject(R.id.home_right)
	private TextView home_right;
	@ViewInject(R.id.home_title_txt)
	private TextView home_title_txt;
	@ViewInject(R.id.bill_declare)
	private TextView bill_declare; // 赎回说明
	@ViewInject(R.id.bill_redeem_confirm)
	private Button bill_redeem_confirm;// 确认赎回
	@ViewInject(R.id.bill_hot_line)
	private TextView bill_hot_line; // 客服电话
	@ViewInject(R.id.bill_all_amount_value)
	private TextView bill_all_amount_value; // 可赎回票据本金总额
	@ViewInject(R.id.bill_redeem_today_pick_value)
	private TextView bill_redeem_today_pick_value; // 今日赎回到帐时间
	@ViewInject(R.id.bill_input_area)
	private ListView bill_input_area; // 金额输入区域

	private BillRedeemListAdapter adapter;
	private List<BillRedeemData> datas;
	private List<String> redeemItemlist;
	private List<String> redeemAmountList;

	//	private MyDialog mDialog; // 赎回确认弹出框

	private String canRedeemAmount; // 赎回金额
	private long billPickTime = 0;// 今日赎回到帐时间
	private boolean canRedeem = false; // 是否可以赎回

	String wapUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@OnClick({R.id.bill_hot_line,R.id.bill_declare,R.id.bill_redeem_confirm})
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bill_hot_line: // 拨打热线
			Intent intent = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:"+AppBasic.app.serviceTel));
			startActivity(intent);
			break;
		case R.id.bill_declare: // 赎回说明跳转
			if(!TextUtils.isEmpty(wapUrl)) {
				Intent intent2 = new Intent(BillRedeemActivity.this,WebActivity.class);
				intent2.putExtra("url", wapUrl);
				intent2.putExtra("name", "赎回说明");
				startActivity(intent2);
			}
			break;
		case R.id.bill_redeem_confirm: // 确认赎回
			doConfirm();
			break;
		default:
			break;
		}
	}

	NormalDialog cd;
	private void show(){
		cd = new NormalDialog(
				BillRedeemActivity.this,
				R.style.calculatorDialog, 
				this, 
				getString(R.string.bill_tips),
				getString(R.string.bill_tips_content),
				"确认",
				"取消");
	}

	/**
	 * 赎回操作
	 */
	private void doConfirm() {
		Map<String, String> map = adapter.getMap();
		Map<String, String> errorMap = adapter.getErrorMap();
		errorMap.clear();
		String mPurchasedAmount = "";
		redeemItemlist = new ArrayList<String>();
		redeemAmountList = new ArrayList<String>();
		if(map.size() <= 0) {
			MyToast.showHMToast(BillRedeemActivity.this, false, "请输入金额");
			return;
		} else {
			Set<String> keys = map.keySet();
			for (String string : keys) {
				for (BillRedeemData billRedeemData : datas) {
					if(billRedeemData.id.equals(string)) {
						mPurchasedAmount = billRedeemData.purchasedAmount;
					}
				}
				if(!TextUtils.isEmpty(map.get(string))) {
					if(Integer.parseInt(map.get(string))%100 != 0 && !Utils.isAllZero(map.get(string))) {
						MyToast.showHMToast(BillRedeemActivity.this, false, "赎回金额必须为100的整数倍");
						errorMap.put(string, "赎回金额必须为100的整数倍");
						continue;
					} else if(Float.parseFloat(mPurchasedAmount==null?"0":mPurchasedAmount) < Float.parseFloat(map.get(string))) {
						MyToast.showHMToast(BillRedeemActivity.this, false, "输入的赎回金额不能大于可用赎回金额");
						errorMap.put(string, "输入的赎回金额不能大于可用赎回金额");
						continue;
					} else {
						redeemItemlist.add(string);
						redeemAmountList.add(map.get(string));
					}
				}
			}
		}
		if(errorMap.size() > 0) {
			adapter.showError(errorMap);
			return;
		}
		if(redeemItemlist.size() > 0) {
			if (cd != null && !cd.isShowing()) {
				cd.show();
			}
		}
	}

	@Override
	public void onPostSuccess(int postId, String msg) {
		Gson gson = new Gson();
		switch (postId) {
		case POST_BILL_REDEEM: // 赎回申请，成功则进入赎回记录，否则提示错误信息
			if (cd !=null && cd.isShowing()) {
				cd.cancel();
				cd = null;
			}

			Type type1 = new TypeToken<InfoWithError<Error>>() {
			}.getType();
			InfoWithError<Error> infoWithError1 = gson.fromJson(msg, type1);
			if(infoWithError1 != null && !TextUtils.isEmpty(infoWithError1.info)) {
				String info = infoWithError1.info;
				MyToast.showHMToast(BillRedeemActivity.this, true, info);
				AppBasic.getInstance().finishCurrentActivity();
				Intent intent = new Intent(BillRedeemActivity.this,WithdrawalsHistoryListActivity.class);
				intent.putExtra("isFromBill", 1);
				startActivity(intent);
			} else {
				bill_redeem_confirm.setText("赎回");
				bill_redeem_confirm.setEnabled(true);
				MyToast.showHMToast(BillRedeemActivity.this, false, infoWithError1.error.message);
			}
			break;
		case GET_BILL_LIST:
			if(datas == null) {
				datas = new ArrayList<BillRedeemData>();
			}
			Type type = new TypeToken<Page<BillRedeemData>>() {
			}.getType();
			Page<BillRedeemData> page = gson.fromJson(msg, type);
			datas = page.records;
			adapter = new BillRedeemListAdapter(datas, getApplicationContext(), bill_redeem_confirm, canRedeem);
			bill_input_area.setAdapter(adapter);
			break;
		default:
			break;
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public void onPostFailure(int postId, String msg) {
		switch (postId) {
		case GET_BILL_LIST:
			Log.e("bill error", msg);
			if (cd != null && cd.isShowing()) {
				cd.cancel();
				cd = null;
			}
			break;
		default:
			break;
		}
		bill_redeem_confirm.setText("赎回");
		bill_redeem_confirm.setEnabled(true);
	}

	@Override
	protected void setParams() {
		layout_home_title.setOnTouchListener(touch);
		home_title_txt.setText(getString(R.string.bill_redeem));
		home_right.setText(getString(R.string.bill_record));
		String tel = AppBasic.app.serviceTel.replaceAll("-", "");
		bill_hot_line.setText("客服电话:"+tel);
		
		//		initMyDialog();
		show();
		
		// 特效，头发的特技
		// 渐变
		AlphaAnimation alphaAnim = new AlphaAnimation(0f, 1.0f);
		alphaAnim.setDuration(1000);

		// 放大
		ScaleAnimation zoomAnim = new ScaleAnimation(0.3f, 1.0f, 0.3f, 1.0f, 
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
		zoomAnim.setDuration(1000);
		alphaAnim.setDuration(2000);
		((ListView)findViewById(R.id.bill_input_area)).setAnimation(alphaAnim);
		((RelativeLayout)findViewById(R.id.bill_sureblank)).setAnimation(alphaAnim);
		alphaAnim.start();
		bill_redeem_confirm.setClickable(false);
		bill_redeem_confirm.setEnabled(false);
		wapUrl =  AppBasic.app.billLinkUrl;
		canRedeemAmount = getIntent().getStringExtra("canRedeemAmount");
		billPickTime = getIntent().getLongExtra("billPickTime", 0);
		canRedeem = getIntent().getBooleanExtra("canRedeem",false);
		if(canRedeem) {
			bill_all_amount_value.setText(canRedeemAmount);
			bill_redeem_today_pick_value.setText(Utils.getDateStringMonthAndDay(billPickTime));
			bill_redeem_confirm.setText("赎回");
			bill_redeem_confirm.setEnabled(true);
		} else {
			bill_all_amount_value.setText(getString(R.string.zero_num));
			bill_redeem_confirm.setText(getString(R.string.bill_not_reatch_time_yet));
			bill_redeem_confirm.setEnabled(false);
		}
		datas = new ArrayList<BillRedeemData>();


		onRequest(GET_BILL_LIST, UrlConstant.BILL_REDEEM_LIST,HttpMethod.GET, null);
	}

	/**
	 * 初始化弹出框
	 */
	/*private void initMyDialog() {
		mDialog = new MyDialog(this, R.layout.view_bill_confirm);
		RelativeLayout dialogContent = (RelativeLayout) mDialog.getContentView();
		Button m_cancle = (Button) dialogContent.findViewById(R.id.m_cancle);
		Button m_sure = (Button) dialogContent.findViewById(R.id.m_sure);
		ImageView m_close = (ImageView) dialogContent.findViewById(R.id.m_close);
		m_cancle.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mDialog.dismiss();
				if(mDialog != null) {
					mDialog = null;
				}
			}
		});
		m_sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				RequestParams params = new RequestParams();
				for (int i = 0; i < redeemItemlist.size(); i++) {
					params.addBodyParameter("redeemItems", redeemItemlist.get(i));
				}
				for (int j = 0; j < redeemAmountList.size(); j++) {
					params.addBodyParameter("redeemAmounts", redeemAmountList.get(j));
				}

				bill_redeem_confirm.setText("赎回中...");
				bill_redeem_confirm.setEnabled(false);     // 点击赎回之后，按钮设置不可点击，防止双击情况发生
				onRequest(POST_BILL_REDEEM, UrlConstant.BILL_REDEEM_DOREDEEM_v3, HttpMethod.POST, params);
				mDialog.dismiss();
				if(mDialog != null) {
					mDialog = null;
				}
			}
		});
		m_close.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mDialog.dismiss();
				if(mDialog != null) {
					mDialog = null;
				}
			}
		});

	}*/

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {
		Intent intent = new Intent(BillRedeemActivity.this,WithdrawalsHistoryListActivity.class);
		intent.putExtra("isFromBill", 1);
		startActivity(intent);
	}

	@Override
	public void closed() {
	}

	@Override
	public void ok() {
		RequestParams params = new RequestParams();
		for (int i = 0; i < redeemItemlist.size(); i++) {
			params.addBodyParameter("redeemItems", redeemItemlist.get(i));
		}
		for (int j = 0; j < redeemAmountList.size(); j++) {
			params.addBodyParameter("redeemAmounts", redeemAmountList.get(j));
		}

		bill_redeem_confirm.setText("赎回中...");
		bill_redeem_confirm.setEnabled(false);     // 点击赎回之后，按钮设置不可点击，防止双击情况发生
		onRequest(POST_BILL_REDEEM, UrlConstant.BILL_REDEEM_DOREDEEM_v3, HttpMethod.POST, params);
	}

	@Override
	public void cancle() {
	}

}
